﻿//  -------------------- iSharePoint -------------------- //
// 
//  Company:	IT Complex, LLC
//  Project:	Smart.Common
//  File name:	WebFormsFormatter.cs
//  Developer:	Solomatov Igor
//  Created:	15.04.2012
// 
//  -------------------- iSharePoint -------------------- //

using System.Web.UI;

namespace Smart.Common.Forms
{
	/// <summary>
	/// SharePoint forms formatter
	/// </summary>
	public abstract class WebFormsFormatter : FormsFormatter
	{
		/// <summary>
		/// SharePoint forms formatter
		/// </summary>
		protected WebFormsFormatter(FormsContext ctx)
			: base(ctx)
		{
		}

		private WebFormPresenter _presenter;

		/// <summary>
		/// WebForm presenter (lazy initialization)
		/// </summary>
		public WebFormPresenter Presenter
		{
			get
			{
				if (_presenter == null)
				{
					_presenter = new WebFormPresenter(Ctx.Meta, Ctx.Mode);

					_presenter.AddCtrlEv += AddCtrl;
				}

				return _presenter;
			}
			set { _presenter = value; }
		}

		/// <summary>
		/// Return current language id
		/// </summary>
		public override int GetCurrentLCID()
		{
			return Presenter.GetCurrentLCID();
		}

		/// <summary>
		/// Instantiate form in container
		/// </summary>
		public override void InstantiateFormInContainer()
		{
			Presenter.Meta = Ctx.Meta;
			Presenter.Mode = Ctx.Mode;

			Presenter.RulesService = GetFormRulesService();
			Presenter.RulesInstance = GetFormRulesInstance();
			Presenter.RulesValues = null;
			Presenter.Tokens = Ctx.Values;

			if (Presenter.RulesService != null && Presenter.RulesInstance != null)
				Presenter.RulesService.LoadInstanceVariables(Presenter.RulesInstance);

			Presenter.AddFormControls((ControlCollection)Ctx.Container.Controls, Ctx.Form);
		}

		/// <summary>
		/// Add event info
		/// </summary>
		public class AddEventInfo
		{
			/// <summary>
			/// Context
			/// </summary>
			public FormsContext Ctx;

			/// <summary>
			/// Formatter
			/// </summary>
			public WebFormsFormatter Formatter;

			/// <summary>
			/// Container
			/// </summary>
			public ControlCollection Container;

			/// <summary>
			/// Metadata
			/// </summary>
			public MetaFormCtrl Meta;

			/// <summary>
			/// Flag whether control was added (result)
			/// </summary>
			public bool Added;
		}

		/// <summary>
		/// Create, init and add UNKNOWN control to container
		/// </summary>
		public virtual bool AddCtrl(ControlCollection container, MetaFormCtrl meta)
		{
			var em = SPServices.EventManager;

			var info = new AddEventInfo
						{
							Ctx = Ctx,
							Formatter = this,
							Meta = meta,
							Added = false
						};

			em.FireEvent(string.Format(Const.EventNames.Forms.AddWebCtrl, Ctx.ServiceName), info);

			return info.Added;
		}
	}
}